package com.hopu.v1.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * Jwt工具类
 */
public class JwtUtils {
    
    //密钥
    private final static String SECRET = "jhhfdgwe5645f6487g4jsbhfueghjb";
    //过期时间（7天）
    private final static Long TIME = 604800000L;
    
    
    /**
     * 生成token
     *
     * @param userId 用户id
     * @return token
     */
    public static String createToken(String userId) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        //将用户id放在主题中
        return JWT.create().withSubject(userId)
                .withExpiresAt(new Date(System.currentTimeMillis() + TIME)).sign(algorithm);
    }
    
    /**
     * 校验token是否合理
     *
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        JWT.require(algorithm).build().verify(token);
        return true;
    }
    
    /**
     * 获取用户id
     *
     * @param token
     * @return
     */
    public static String getUserId(String token) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        DecodedJWT decodedJWT = JWT.require(algorithm).build().verify(token);
        return decodedJWT.getSubject();
    }
    
}
